<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2019/1/10
 * Time: 17:42
 */

namespace app\api\model;


class Follow extends BaseModel
{
    protected  $autoWriteTimestamp = true;

    /**
     * 与user表一对一1关系
     * @return \think\model\relation\BelongsTo
     */
    public function user(){
        return $this->belongsTo('User','user_id','id');
    }
    /**
     * 获取跟进记录
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserbyOrder($wu_id){
        $result =  self::where("wu_id",'=',$wu_id)
                ->field('user_id,max(create_time) time')
                ->group('user_id')
                ->with(['user'])
                ->order('time','desc')
                ->select();
        foreach ($result as $value){
            if (!empty($value->user)){
                $value->user->visible(['id','nickname','avatar_url']);
            }
        }
        return $result;
    }

    /**
     * 创建跟进记录
     * @param $data
     * @return $this
     */
    public  function createFollow($data){
        $count = self::where('wu_id','=',$data['wu_id'])
            ->where('user_id','=',$data['user_id'])
            ->count();
        $data['times'] = $count+1;
        return self::create($data);
    }

    /**
     * 获取行为统计列表
     * @param $uid
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getFollow($uid,$wu_id,$size,$page){
        $list = self::where('wu_id','=',$wu_id)
            ->where('user_id','=',$uid)
            ->with(['user'])
            ->limit(($page-1)*$size,$size)
            ->order('create_time desc')
            ->select();
        foreach ($list as $value){
            $item =  $value->visible(['content','create_time','user']);
            $item->user->visible(['nickname','avatar_url']);
        }
        return $list;
    }

    /**
     * 获取所有统计信息
     * @param $wu_ids
     * @param $time
     * @return int|string
     */
    public static function getAllNum($wu_ids,$time){
        $num = self::Where('wu_id','in',$wu_ids)
            ->where('create_time','>',$time)
            ->count();
        return $num;
    }
    /**
     * 返回对应天数结果
     * @param $id
     * @param $time
     * @return mixed
     */
    public static function getAllFollowList($wu_ids,$time){
        $num = self::Where('wu_id','in',$wu_ids)
            ->where('create_time','>=',$time)
            ->field("FROM_UNIXTIME(update_time,'%m-%d') days,count(id) num")
            ->group('days')
            ->select();
        return $num;
    }


}